# PowerShell script to build Android NDK C++ executable

$ErrorActionPreference = "Stop"

# Set NDK path and target ABI
# D:\Android\Sdk\ndk\29.0.13599879
# E:\Android\Sdk\ndk\21.1.6352462
$NDK = $env:ANDROID_NDK_HOME
if (-not $NDK) {
    $NDK = "E:\Android\Sdk\ndk\21.1.6352462"
}
$API = 21
$ABI = "arm64-v8a"

# Compiler path
$TOOLCHAIN = Join-Path $NDK "toolchains\llvm\prebuilt\windows-x86_64"
$CC = Join-Path $TOOLCHAIN "bin\aarch64-linux-android$API-clang++.cmd"


$build_dir = "$PSScriptRoot/build"
$release_dir = "$PSScriptRoot/release"
$exePath = "$release_dir/android"
# Define the array of directories to clean and create
$directories = @($release_dir, $build_dir)

# Clean directories
foreach ($dir in $directories) {
    if (Test-Path $dir) {
        Remove-Item $dir -Recurse -Force -ErrorAction Stop
    }
}

# Create directories
foreach ($dir in $directories) {
    New-Item -Path $dir -ItemType Directory -Force | Out-Null
}

$DEFINES = @(
    "-DPORT=12345"
)

Write-Host "Compiling $exePath ..."

# Add include directory
$INCLUDES = @(
    "-I$PSScriptRoot/include"
)

# Find all cpp files in src, excluding OHOSDevice.cpp
$cppFiles = Get-ChildItem "$PSScriptRoot/src" -Filter *.cpp | Where-Object { $_.Name -ne "OHOSDevice.cpp" } | ForEach-Object { $_.FullName }
$objFiles = @()
foreach ($cpp in $cppFiles) {
    $obj = Join-Path $build_dir ( [System.IO.Path]::GetFileNameWithoutExtension($cpp) + ".o" )
    $CompileArgs = $DEFINES + $INCLUDES + @("-c", $cpp, "-o", $obj)
    & $CC $CompileArgs
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Compilation failed for $cpp!"
        exit 1
    }
    $objFiles += $obj
}

# Link all object files
Write-Host "Linking executable..."
$LinkArgs = $objFiles + @("-static-libstdc++", "-llog", "-o", $exePath)
& $CC $LinkArgs

if ($LASTEXITCODE -ne 0) {
    Write-Error "Linking failed!"
    exit 1
}

& "$NDK/toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-strip.exe" $exePath

Write-Host "Build done. Output: $exePath"